/**
 * 
 */
package com.effectivsocial.service.impl;

import java.util.Locale;

import javax.inject.Inject;
import javax.inject.Named;
import javax.mail.internet.MimeMessage;

import lombok.extern.slf4j.Slf4j;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.effectivsocial.domain.User;
import com.effectivsocial.service.api.EmailService;

/**
 * @author Dhrubo
 *
 */
@Named
@Slf4j
public class EmailServiceImpl implements EmailService{
	
	@Inject
    private JavaMailSender mailSender;
    
	@Inject
    private TemplateEngine templateEngine;
	
	public void sendOnRegister(User user, final Locale locale) {
		 // Prepare the evaluation context
        final Context ctx = new Context(locale);
        ctx.setVariable("user", user);
        
        
        // Prepare message using a Spring helper
        final MimeMessage mimeMessage = mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        try {
			message.setSubject("Welcome to effectivSOCIAL");
			message.setFrom("info@effectivcrm.com");
	        message.setTo(user.getEmail());

	        // Create the HTML body using Thymeleaf
	        final String htmlContent = templateEngine.process("registration-email", ctx);
	        
	        log.info("Mail content - {}" , htmlContent);
	        
	        message.setText(htmlContent, true );/* isHtml */
	        
	        // Send email
	        mailSender.send(mimeMessage);
		} catch (Exception e) {
			log.info("Unable to send registration email.");
			log.error("Error ", e);
		}
        
		
	}

}
